package com.cheetah.start.common.plugin.log;


import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.OS;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.cheetah.start.common.utils.MyIpUtil;
import com.cheetah.start.common.utils.MyServletUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制台记录所有接口请求
 *
 * @author xjhmwj
 * @date 2021/1/25 14:12
 */
@Aspect
@Component
@Slf4j
public class ConsoleLogAspect {

    @Autowired
    private Ip2regionSearcher regionSearcher;

    @Pointcut("execution(public * com.cheetah.start..*.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {

    }


    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
    }

    @Around("webLog()")
    public Object timing(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object;
        long start = System.currentTimeMillis();
        MDC.put("logTrackId", IdUtil.simpleUUID().substring(0, 6));
        object = joinPoint.proceed();
        long l = System.currentTimeMillis() - start;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String param = MyServletUtil.getParam(request);
        UserAgent parse = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String browerName = "";
        String version = "";
        OS os = null;
        if (parse != null) {
            Browser browser = parse.getBrowser();
            if (browser != null) {
                browerName = browser.getName();
            }
            version = parse.getVersion();
            os = parse.getOs();
        }

        // 处理完请求，返回内容
        StringBuilder s = new StringBuilder();
        if (object != null) {
            s.append(object.toString());
            // 给太长的内容截取掉,日志太长不好看
            if (s.length() > 500) {
                s.delete(500, s.length() - 1);
                s.append(".....");
            }
        }
        long l1 = System.nanoTime();
        String ipAddress = MyIpUtil.getIpNotHavePort(request);
        String address = regionSearcher.getAddress(ipAddress);

        log.info("接口地址:[{}],请求方式:[{}],参数:{}\nIP地址:[{}],其他信息:[{}],接口耗时:[{}]ms\n打印耗时:[{}]μs,请求结果:[{}]",
                request.getRequestURI(),
                request.getMethod(),
                param,
                ipAddress + "|" + address,
                browerName + "|" + version + "|" + os, l, (System.nanoTime() - l1) / 1000,
                s
        );
        if (l > 2000) {
            log.warn("注意:请求耗时过长,耗时:[{}]MS", l);
        }
        MDC.clear();
        return object;
    }

}
